package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 设备管理Service业务层处理
 *
 * @author yiyunyun
 * @date 2025-01-16
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private Device device;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        //请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(200);
        request.setCurrentPage(1);

        aliIoTConfigProperties.setIotInstanceId("iot-06z00b1spcnpumg");
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //调用第三方查询产品列表
        QueryProductListResponse response ;
        try {
            response =client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //判断，如果数据为空，则中断请求
        if (!response.getBody().success){
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));



    }


    /**
     * 查询所有产品列表
     *  @return 产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        //如果数据为空，则返回一个空集合
        if (StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr,ProductVo.class);
    }

    /**
     *"注册设备"
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) throws Exception {

        //查询设备名称是否重复(存在多个)，存在抛出异常（结束）
        Long count = deviceMapper.selectCount(Wrappers
                .<Device>lambdaQuery()
                .eq(Device::getDeviceName,deviceDto.getDeviceName()));
        if (count >0 ){
            throw new BaseException("设备名称重复");
        }
//        新增设备存入物联网平台
        RegisterDeviceRequest deviceRequest = deviceDto.getRegisterDeviceRequest();
        deviceRequest.setProductKey(deviceDto.getProductKey());
        deviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse registerDeviceResponse = client.registerDevice(deviceRequest);
        if (!registerDeviceResponse.getBody().success){
            throw new BaseException("设备添加失败");
        }
        try {
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,device);
        device.setProductName(registerDeviceResponse.getBody().getData().getIotId());
        //不存在就查询产品名称信息，设备需要填充check_inproductName(调用阿里云)
        QueryProductRequest request = new QueryProductRequest();
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse response = client.queryProduct(request);
        if (!response.getBody().success){
            throw new BaseException("产品信息异常！");
        }
        device.setProductKey(response.getBody().getData().getProductName());

        //判断位置类型，类型是随声设备，则设置无力位置为-1
        if (deviceDto.getLocationType().intValue()==0){
            device.setPhysicalLocationType(-1);
        }
        //保存数据到数据库
        deviceMapper.insert(device);
        }catch (Exception e){
//            保存数据发生异常时，代码补偿删除阿里云IOT云平台添加的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
            deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
            deleteDeviceRequest.setIotId(registerDeviceResponse.getBody().getData().getIotId());
            client.deleteDevice(deleteDeviceRequest);
            throw  new RuntimeException(e);
        }

    }

    /**
     *  查询设备详情
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //查询iot平台中的设备数据
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryDeviceDetailRequest.setProductKey(deviceDto.getProductKey());
        queryDeviceDetailRequest.setIotId(deviceDto.getIotId());
        QueryDeviceDetailResponse response;
        try {
             response = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
           throw  new BaseException("物联网接口 - 查询设备，调用失败");
        }
        //安全校验
        if (!response.getBody().success){
            throw  new RuntimeException("物联网接口 - 查询设备，调用失败");
        }
        //查询表中的数据
        Device one = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));

        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        //合并
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data =response.getBody().getData();
        BeanUtil.copyProperties(data,deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 查询指定设备的物模型运行状态
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //查询设备属性状态
        QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse;
        try {
            queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }
        if (!queryDevicePropertyStatusResponse.getBody().success){
            throw new BaseException(queryDevicePropertyStatusResponse.getBody().getErrorMessage());
        }
        //封装数据返回
        return AjaxResult.success(queryDevicePropertyStatusResponse.getBody().getData());
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse  response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 删除设备
     */
    @Override
    public void deleteDevice(DeviceDto deviceDto) throws Exception {
//        删除本地
        int count = deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()).eq(Device::getProductKey, deviceDto.getProductKey()));
//        删除远程
        if (count>0){
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.setIotId(deviceDto.getIotId());
            request.setProductKey(deviceDto.getProductKey());
            request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

            DeleteDeviceResponse response = client.deleteDevice(request);
            if (!response.getBody().success){
                throw new BaseException("设备删除失败");
            }


        }
    }
    /**
     * 修改设备
     */
    @Override
    public void updateDeviceInfo(DeviceDto deviceDto) throws Exception {
        //1、修改本地
        //1.1将DT0转成实体类
        Device device = new Device();
        BeanUtil.copyProperties(deviceDto,device);
        //1.2根据设备类型确定屋里位置类型
        if (deviceDto.getLocationType() == 0){
            device.setPhysicalLocationType(-1);
        }
        int count = deviceMapper.updateById(device);
        //2、修改云端
        if (count>0){
            //2.1、封装数据
            BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
            request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            //封装需要修改的设备名字
            BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceOne =
                    new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
            deviceOne.setDeviceName(deviceDto.getDeviceName());
            deviceOne.setIotId(deviceDto.getIotId());
            deviceOne.setProductKey(deviceDto.getProductKey());
            deviceOne.setNickname(deviceDto.getNickname());

            List< BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list = new ArrayList<>();
            list.add(deviceOne);
            request.setDeviceNicknameInfo(list);
            //2)执行修改
            BatchUpdateDeviceNicknameResponse response = client.batchUpdateDeviceNickname(request);
            // 3、修改失败，问滚本地
            if (!response.getBody().success){
                throw new BaseException("设备信息修改失败");
            }

        }



    }

}
